package com.wjc.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.wjc.config.AlipayConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Controller
public class AlipayController {
    /**
     * 结算界面
     * @return
     */
    @RequestMapping("/PayPage")
    @ResponseBody
    public String payController(HttpServletRequest request, HttpServletResponse
            response) throws IOException, ParseException {
//可以在这里进行订单状态的设置，对数据库操作
//获得初始化的AlipayClient
        AlipayClient alipayClient=new
                DefaultAlipayClient(AlipayConfig.gatewayUrl,
                AlipayConfig.APP_ID,
                AlipayConfig.APP_PRIVATE_KEY,
                "json",AlipayConfig.CHARSET,
                AlipayConfig.ALIPAY_PUBLIC_KEY,
                AlipayConfig.sign_type);
//设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//同步回调，如果本地调度只会走同步，这里的界面就是你付款后跳转的界面
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
//异步回调，没有服务器实际上我们用不到
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
//订单名称，必填
        String subject=request.getParameter("注意：test");
//商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no =request.getParameter("Order");
//付款金额，必填 ShopName
        String total_amount =request.getParameter("Money");
//商品描述，可空
        String body ="购物测试";
// 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如1.5h，可转换为 90m。
        String timeout_express = "1c";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no +
                "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
/* //请求
String url = "";
try {
url = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生
成表单
} catch (AlipayApiException e) {
e.printStackTrace();
}
response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
return url;*/
//这两种方式都是可以的，就是上面那种可能很容易报错，看运气是否成功
//请求
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
        return form;
    }
    /**
     * 同步跳转
     * @param request
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/returnUrl")
    public ModelAndView returnUrl(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView();
// 获取支付宝GET过来反馈信息（官方固定代码）
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator();
             iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] :
                        valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
            //调用sdk验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type);
// 调用SDK验证签名
// 返回界面
        if (signVerified) {
            String orderNo = new String(request.getParameter("out_trade_no"));
//大家可以在里更新你数据库中的数据状态，这样就能做到跟项目结合了
            System.out.println("前往支付成功页面");
            //4、前台页面可能拿来测试一下你的进入付款是否跳转成功
//使用重定向可以使你的页面样式不丢失
            mav.setViewName("redirect:itemOrder_my");
        } else {
            System.out.println("前往支付失败页面");
            mav.setViewName("itemOrder/fail");
        }
        return mav;
    }
    /**
     * 支付宝服务器异步通知
     *
     * @param request
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/notifyUrl")
    public void notifyUrl(HttpServletRequest request) throws Exception {
// 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator();
             iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] :
                        valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.sign_type);
// 调用SDK验证签名
        if (signVerified) { // 验证成功 更新订单信息
            System.out.println("异步通知成功");
// 商户订单号
            String out_trade_no = request.getParameter("out_trade_no");
// 交易状态
            String trade_status = request.getParameter("trade_status");
        } else {
            System.out.println("异步通知失败");
        }
    }
}